package test2;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    public DatagramSocket serverSocket = null;
    public UdpEchoServer(int port) throws SocketException {
        this.serverSocket = new DatagramSocket(port);
    }
    public void strat() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],0,4096);
            serverSocket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                requestPacket.getSocketAddress());
            serverSocket.send(responsePacket);
            System.out.printf("[%s,%d],req=%s,resq=%s",requestPacket.getAddress(),requestPacket.getPort(),
                    request,response);
            System.out.println("");
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.strat();
    }
}
